package cn.tedu._06article.base.exception;

import cn.tedu._06article.base.response.JsonResult;
import cn.tedu._06article.base.response.StatusCode;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult doHandler(MethodArgumentNotValidException ex) {
        String data = ex.getBindingResult().getFieldError().getDefaultMessage();
        log.error("MethodArgumentNotValidException：" + data);
        return  new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public JsonResult doHandler(ConstraintViolationException ex) {
        String data = ex.getConstraintViolations().iterator().next().getMessage();
        log.error("ConstraintViolationException：" + data);
        return  new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }


    @ExceptionHandler(RuntimeException.class)
    public JsonResult doHandler(RuntimeException ex) {
        log.error(ex.getMessage());
        ex.printStackTrace();
        return new JsonResult(StatusCode.OPERATION_FAILED, ex.getMessage());
    }
}
